package com.tankwar.transport;

import com.swak.exception.RemotingException;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeHandler;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.ExchangeServer;
import com.swak.reactivex.transport.Exchangers;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;

public class TankwarServer {

	private ExchangeServer server;
	private ExchangeHandler exchangeHandler = new ExchangeHandlerAdapter() {
		@Override
		public void received(Channel channel, Object message) throws RemotingException {
			TankwarServer.this.received(channel, message);
		}

		@Override
		public void connected(Channel channel) throws RemotingException {
			super.connected(channel);
			System.out.println("有客户端连接");
		}

		@Override
		public void disconnected(Channel channel) throws RemotingException {
			super.disconnected(channel);
			System.out.println("客户端关闭连接");
		}
	};

	public TankwarServer(URL url, LoopResources resources) {
		this.server = Exchangers.bind(url, resources, exchangeHandler);
	}

	public void start() {
		this.server.start();
	}

	public void close() {
		this.server.close();
	}

	/**
	 * 外部可以调用此来发送数据
	 * 
	 * @param message
	 * @throws RemotingException
	 */
	public void sent(Object message) throws RemotingException {
		server.send(message, false);
	}

	/**
	 * 收到数据处理
	 * 
	 * @param channel
	 * @param message
	 */
	private void received(Channel channel, Object message) {
		System.out.println("收到数据");
	}
}
